<template>
  <el-container style="width: 900px; margin: 0 auto;">
    <el-header style="display: flex;">
      <h2>学生信息管理</h2>
      <div>欢迎您，{{ authStore.user.realName }}</div>
    </el-header>
    <el-main>
      <el-row justify="space-between" :gutter="10">
        <el-col :span="5">
          <SearchForm @do-search="doSearch"></SearchForm>
        </el-col>
        <el-col :span="1">
          <el-button :icon="Plus" 
            circle type="primary" @click="onAddButtonClick">    
          </el-button>
        </el-col>
        
      </el-row>
      <div v-if="students.length == 0">暂无学生信息</div>
    <el-table v-else :data="studentsOnDisplay" style="width: 100%">
      <el-table-column prop="studentNo" label="学号" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="studentClass" label="班级" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="mobileNumber" label="联系电话"></el-table-column>
      <el-table-column prop="dob" label="出生日期">
        <template #default="scope">
          {{ dayjs(scope.row.dob).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="修改" width="90">
        <template #default="scope">
          <el-button type="primary" link @click="goEdit(scope.row.studentNo)">修改</el-button>
          <!-- <a :href="'/student-edit/' + scope.row.studentNo"></a> -->
        </template>
      </el-table-column>
      <el-table-column label="删除" width="90">
        <template #default="scope">
          <el-button type="danger" link 
          @click="onDeleteButtonClick(scope.row.studentNo)">
            删除
          </el-button>          
        </template>
      </el-table-column>
    </el-table>
    
    <div style="display: flex; justify-content: space-between;">
      <div>
        共有{{ studentStat.totalCount }}名学生，其中{{ studentStat.maleCount }} 名男生，{{ studentStat.femaleCount }}名女生。
      </div>
      <div v-if="searchKeyword == ''">
        <ul class="pagination">
          <li v-for="i in totalPages" :class="{active: i == page}">
            <a @click.prevent="goPage(i)">{{ i }}</a>
          </li>
        </ul>
      </div>
    </div>
    </el-main>
  </el-container>  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import router from '@/router.js';
import { useAuthStore } from '@/store/auth.store.js';

const authStore = useAuthStore();

// 导入AddSTudent组件，@代码src目录
import SearchForm from '@/components/SearchForm.vue'

const students = ref([]);
const page = ref(1);
const PAGE_SIZE = 6;

const searchKeyword = ref('')

const totalPages = computed(() => {
  return Math.ceil(students.value.length / PAGE_SIZE);
})
const studentsOnDisplay = computed(() => {
  if(searchKeyword.value == '') {
    let start = (page.value - 1) * PAGE_SIZE;
    // 如果是最后一页，end是数组的length，否则为start + PAGE_SIZE
    let end = page.value == totalPages ? students.value.length : start + PAGE_SIZE;
    // console.log(start);
    // console.log(end);
    return students.value.slice(start, end);
  } else {
    return students.value.filter(s => s.name.startsWith(searchKeyword.value))
  }
  
})
const studentStat = computed(() => {
  let maleCount = 0;
  students.value.forEach(s => {
    if(s.gender == '男') {
      maleCount++;
    }
  });
  return {
    totalCount: students.value.length,
    maleCount,
    femaleCount: students.value.length - maleCount
  }
})

async function onDeleteButtonClick(studentNo) {
  ElMessageBox.confirm(
    `确定要删除学生(学号${studentNo})吗?`,
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    deleteStudent(studentNo);
  })
  // .catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: 'Delete canceled',
  //   })
  // })
}

async function deleteStudent(studentNo) {
  const api = '/api/students/delete-student';
  try {
    await axios.get(api, { params: { "student-no": studentNo}});
    ElMessage({
      type: 'success',
      message: '已成功删除。',
    })
    loadStudentData();
  } catch (err) {
    ElMessage({
      type: 'error',
      message: '删除失败，访问后端接口错误。',
      showClose: true,
      duration: 0
    })
  } 
}
function onAddButtonClick() {
  router.push('/students/new-student');
}

function goPage(i) {
  page.value = i;
}

function doSearch(keyword) {
  searchKeyword.value = keyword;
}

function goEdit(studentNo) {
  router.push('/student-edit/' + studentNo);
}

onMounted(() => {
  loadStudentData();
})

function loadStudentData() {
  let api = '/api/students/get-all-students';
  axios.get(api)
  .then((res) => {
    students.value = res.data;
  })
  .catch(error => {
    ElMessage({
      message: '访问数据失败。',
      type: 'error',
      showClose: true,
      duration: 0
    })
    console.error(error);
  })
}
</script>

<style lang="scss">
.pagination {
  display: flex;
  list-style: none;
  li {
    margin: 0 0.5rem;
    a {
      cursor: pointer;
      color: rgb(67, 121, 221);
      &:hover {
        text-decoration: underline;
      }
    }
    &.active {
      a {
        color: rgb(19, 94, 169);
        font-weight: bold;
      }
    }
  }
}
</style>